Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
In for loop of fetch requests, how do you pass "i" value into body payload that's been defined as template literal outside the loop?

I want to make multiple fetch requests, each request has a different payload, studentID in this example. Every loop changes the studentID, but the payload is defined as a template literal variable outside the loop for readability. Is there a way to get for loop iterator value to the payload (defined outside)?

var payload=`{"studentID": ${studentID}}` //expecting studentID to be iterated in loop
var myInit = {
    method: 'POST',
    headers: {
       'Accept': 'application/json, text/plain, */*',
       'Content-Type': 'application/json'
    },
    body: payload
};

for(var studentID = 0; studentID <= 10; studentID++) {
    fetch(URI, myInit)
    .then( r => r.json() )
    .then( r => console.log(r) 
    .catch(e => console.log(e));
}

studentID values (0,1,2,3...) cannot get into myInit's payload template.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Make a function instead.

const makeInit = studentID => ({
    method: 'POST',
    headers: {
       'Accept': 'application/json, text/plain, */*',
       'Content-Type': 'application/json'
    },
    body: `{"studentID": ${studentID}}`
});
for(var studentID = 0; studentID <= 10; studentID++) {
    fetch(URI, makeInit(studentID))

Maybe don't stringify manually.

const makeInit = studentID => ({
    method: 'POST',
    headers: {
       'Accept': 'application/json, text/plain, */*',
       'Content-Type': 'application/json'
    },
    body: JSON.stringify({ studentID })
});
for(var studentID = 0; studentID <= 10; studentID++) {
    fetch(URI, makeInit(studentID))
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda